from PyQt5.QtCore import Qt,pyqtSignal
from PyQt5.QtWidgets import QApplication, QListWidget, QListWidgetItem
# from myQlist import MyListWidget
class MyListWidget(QListWidget):
    exchange_signal = pyqtSignal(int, int) # 列表中的元素发生交换
    def __init__(self,parent=None):
        super().__init__(parent)
        #self.setDragDropMode(QListWidget.DragDrop)


    def dropEvent(self, event):
        print("Drop event")

        # # 获取拖放数据
        pos=event.pos()  #获取拖入事件的坐标
        current_item=self.itemAt(pos)  #获取当前坐标下的item
        current_index=self.indexFromItem(current_item)  #获取该item的index
        current_row=current_index.row()  #获取行数
        print('目标位置:',current_row)
        if current_row==-1:
            print("无效位置")
            return
        source_Widget=event.source()  #获取拖入item的父组件
        items=source_Widget.selectedItems() #获取所有的拖入item
        for i in items:
            
            ori_row=source_Widget.indexFromItem(i).row() # 行号
            item = source_Widget.takeItem(ori_row)  #实时移除来源item
            # item和i是同一个东西

            self.insertItem(current_row,i)  #插入本listwidget
            self.exchange_signal.emit(ori_row,current_row)  #发射信号
           

    # def dragMoveEvent(self, event):
    #     print("Drag move event")

    #     # 接受拖放数据
    #     if event.mimeData().hasFormat("application/x-qabstractitemmodeldatalist"):
    #         event.acceptProposedAction()

if __name__ == "__main__":
    app = QApplication([])

    list_widget = MyListWidget()

    # 添加列表项
    for i in range(5):
        item = QListWidgetItem(f"Item {i}")
        list_widget.addItem(item)

    list_widget.show()
    app.exec_()
